//
//  WBStatusViewModel.swift
//  XLWB
//
//  Created by MacBook on 16/7/6.
//  Copyright © 2016年 MacBook. All rights reserved.
/* 关于表格的性能优化
 
 - 尽量少计算，所有需要的素材提前计算好！
 - 控件上不要设置圆角半径，所有图像渲染的属性，都要注意！
 - 不要动态创建控件，所有需要的控件，都要提前创建好，在显示的时候，根据数据隐藏／显示！
 - Cell 中控件的层次越少越好，数量越少越好！
 - 要测量，不要猜测！
*/

import Foundation

//单条微博的视图模型
class WBStatusViewModel: CustomStringConvertible {

    //微博模型
    var status: WBStatus
    
    //会员图标----存储型属性(用内存换cpu)
    var menberIcon: UIImage?
    
    //认证类型
    var vipIocn: UIImage?
    
    //转发文字
    var retweetedStr: String?
    //评论文字
    var commentStr: String?
    //点赞文字
    var likeStr: String?
    
    //来源字符串
//    var sourceStr: String?
    
    //被转发微博的文字
    var retweetedText: String?
    
    //行高
    var rowHeight: CGFloat = 0
    
    //如果是被转发的微博,原创微博一定没有图
    var picURLs: [WBStatusPicture]? {
    
        return status.retweeted_status?.pic_urls ?? status.pic_urls
    
    }
    
    // 微博正文的属性文本
    var statusAttrText: AttributedString?
    // 转发文字的属性文本
    var retweetedAttrText: AttributedString?
    
    //配图视图大小
    var pictureViewSize = CGSize()
    /// 构造函数
    /// - parameter model: 微博模型
    /// - returns: 微博的视图模型

    init(model: WBStatus) {
        
        self.status = model
        
        // 直接计算出会员图标/会员等级 0-6
        if  model.user?.mbrank > 0 && model.user?.mbrank < 7 {
            let imageName = "common_icon_membership_level\(model.user?.mbrank ?? 1)"
            
            menberIcon = UIImage(named: imageName)
        }
        
        //认证图标
        switch model.user?.verified_type ?? -1 {
        case 0:
            vipIocn = UIImage(named:"avatar_vip")
        case 2, 3, 5:
            vipIocn = UIImage(named: "avatar_enterprise_vip")
        case 220:
            vipIocn = UIImage(named: "avatar_grassroot")
        default:
            break
        }
        
        // 测试超过一万的数字
        // model.reposts_count = Int(arc4random_uniform(100000))

        retweetedStr = countString(count: model.reposts_count, defaultStr: "转发")
        commentStr = countString(count: model.comments_count, defaultStr: "评论")
        likeStr = countString(count: model.attitudes_count, defaultStr: "赞")
        
        //计算配图大小(有原创计算原创,有转发计算转发)
        pictureViewSize = calcPictureViewSize(count: picURLs?.count)

        //设置被转发微博的文字
//        retweetedText = "@" + (status.retweeted_status?.user?.screen_name ?? "")
        // 设置微博文本
        let originalFont = UIFont.systemFont(ofSize: 15)
        let retweetedFont = UIFont.systemFont(ofSize: 14)
            
        // 微博正文的属性文本
        statusAttrText = DDEmoticonManager.shared.emoticonString(string: model.text ?? "", font: originalFont)
        
        // 设置被转发微博的属性文本
        let rText = "@" + (status.retweeted_status?.user?.screen_name ?? "")
            + ":"
            + (status.retweeted_status?.text ?? "")
        retweetedAttrText = DDEmoticonManager.shared.emoticonString(string: rText, font: retweetedFont)

        //设置来源字符串
//        sourceStr = "来自 " + (model.source?.dd_href()?.text ?? "")
        
        //计算行高
        updateRowHeight()
    }
    
    var description: String {
    
        return status.description
    
    }
    
    //根据当前的视图模型内容计算行高
    func updateRowHeight() {
    
        // 原创微博：顶部分隔视图(12) + 间距(12) + 图像的高度(34) + 间距(12) + 正文高度(需要计算) + 配图视图高度(计算) + 间距(12) ＋ 底部视图高度(35)
        // 被转发微博：顶部分隔视图(12) + 间距(12) + 图像的高度(34) + 间距(12) + 正文高度(需要计算) + 间距(12)+间距(12)+转发文本高度(需要计算) + 配图视图高度(计算) + 间距(12) ＋ 底部视图高度(35)

        let margin: CGFloat = 12
        let iconHeight: CGFloat = 34
        let toolbarHeight: CGFloat = 35
        
        var height: CGFloat = 0
        
        let viewSize = CGSize(width: UIScreen.cz_screenWidth() - 2 * margin, height: CGFloat(MAXFLOAT))
//        let originalFont = UIFont.systemFont(ofSize: 15)
//        let retweetedFont = UIFont.systemFont(ofSize: 14)
        
        //1.计算顶部位置
        height = 2 * margin + iconHeight + margin
        
        //2.正文高度
        if let text = status.text {
            //预期尺寸,宽度固定,高度尽量大
            //选项,换行文本,统一使用usesLineFragmentOrigin
            //attributes: 指定字体字典
//            height += (text as NSString).boundingRect(with: viewSize, options: [.usesLineFragmentOrigin], attributes: [NSFontAttributeName: originalFont], context: nil).height
            height += text.boundingRect(with: viewSize, options: [.usesLineFragmentOrigin], context: nil).height

        }
    
    
        //3.判断是都转发微博
        if status.retweeted_status != nil {
            height += 2 * margin
            
             if let text = retweetedAttrText {
//                height += (text as NSString).boundingRect(with: viewSize, options: [.usesLineFragmentOrigin], attributes: [NSFontAttributeName: retweetedFont], context: nil).height
                height += text.boundingRect(with: viewSize, options: [.usesLineFragmentOrigin], context: nil).height

            }
        }
        
        //4.配图视图
        height += pictureViewSize.height
        height += margin
        
        //5.底部工具栏
        height += toolbarHeight
        
        //6.使用属性记录
        rowHeight = height

    }
    
    //使用单个图像,更新视图的大小
    func updateSingleIamgeSize(image: UIImage) {
    
        var size = image.size
        
        let maxWith: CGFloat = 300
        let minWith: CGFloat = 10
        
        // 过宽图像处理
        if size.width > maxWith {
            // 设置最大宽度
            size.width = maxWith
            // 等比例调整高度
            size.height = size.width * image.size.height / image.size.width
        }
        // 过窄图像处理
        if size.width < minWith {
            size.width = minWith
            
            // 要特殊处理高度，否则高度太大
            size.height = size.width * image.size.height / image.size.width / 4
        }

        
        
        
        //尺寸需要增加顶部的12歌点,方便布局
        size.height += WBStatusPictureViewOutterMargin
        pictureViewSize = size
    
    
    }
    
    //计算指定数量的图片对应的配图视图大小
    private func calcPictureViewSize(count: Int?) -> CGSize {
    
//        return CGSize(width: 100, height: 300)
        
        if count == 0 || count == nil {
            return CGSize()
        }
        
        //2.计算高度
        let row = (count! - 1) / 3 + 1
        
        //根据行高计算高度
        var height = WBStatusPictureViewOutterMargin
        height += CGFloat(row) * WBStatusPictureItemWidth
        height += CGFloat(row - 1) * WBStatusPictureViewInnerMargin
        
        return CGSize(width: WBStatusPictureViewWidth,height: height)
    }
    
    private func countString(count: Int, defaultStr: String) -> String {
    
        if count == 0 {
            return defaultStr
        }
    
        if count < 10000 {
            return count.description
        }
    
    return String(format: "%.02f 万", Double(count) / 10000)
    }
}
